/*
 This file is part of WebHUD.
 
 WebHUD is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.
 
 WebHUD is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with WebHUD.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "LocationChangeHandler+WHWebFrameLoadDelegate.h"
#import "Constants.h"
#import "WHController.h"
#import "WHHelper.h"

// Fake src definition, because we know DOMHTMLImageElement and DOMHTMLEmbedElement implement it
@interface DOMElement (WHDOMElement)
- (NSString *)href;
- (NSString *)rel;
- (NSString *)title;
@end

@implementation LocationChangeHandler (WHWebFrameLoadDelegate)

+ (BOOL)swizzle
{
	return [self overrideMethods:[NSArray arrayWithObject:@"webView:didFinishLoadForFrame:"]];
}


- (void)_webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{

	if ( frame != [sender mainFrame]) {
		NSLog(@"Not main frame -- ignoring");
		goto DONE;
	}
	
	DOMXPathResult* elements = [[frame DOMDocument] evaluate:@"//link[@rel='hud']"
												 contextNode:[[frame DOMDocument] documentElement]
													resolver:nil
														type:DOM_ANY_TYPE 
													inResult:nil];
	
	NSMutableDictionary *urls = [[NSMutableDictionary alloc] init];
	NSMutableArray		*order = [[NSMutableArray alloc] init];
	
	DOMElement *element;
	while (element = (DOMElement *)[elements iterateNext]) {
		if ([element respondsToSelector:@selector(href)] &&
		    [element respondsToSelector:@selector(title)] &&
		    [element respondsToSelector:@selector(rel)] ) {
			NSLog(@"WebHub: found <link href=%@ rel=%@ title=%@>",
					[element href], [element rel], [element title]);
			
			[urls setObject:[element href] forKey: [element title]];
			[order addObject: [element title]];
		}
	}
	
#ifdef DEBUG
	for ( NSString *title in urls) {
		NSLog(@"dict: key %@ value %@", title, [urls objectForKey: title]);
	}
#endif

	if ([urls count]) {
		[[WHController sharedController] setUrls: urls];
		[[WHController sharedController] setOrder: order];
		[[WHController sharedController] showHUDForWebView: sender
												  andFrame: frame];
	} else {
		[[[WHController sharedController] panel] setIsVisible: NO];
	}

DONE:
	[self _webView:sender didFinishLoadForFrame:frame];
}

@end
